#define USE_LOCAL_LOG_LEVEL

#include "ursax.h"
#include "log.h"
#include "utcache.h"
#include "endpoints.h"
#include "st-redis.h"
#include "redis-single.h"

static struct RedisSTAttach *singleConn = NULL;

int
redis_single_connect(void)
{
	char ip[64];
	uint16_t port;
	int tried = 0;
	do {
		memset(ip, 0, sizeof(ip));
		get_a_redis_server_str(ip, &port);
	} while (6379 != port && tried++ < 20); /**< single cluster must use 6379 for mix mode */

	LOG_DEBUG("[%s:%d] NEW REDIS SINGLE CLIENT IP[%s] PORT[%d]",
									__func__, __LINE__, ip, port);

	if (6379 == port) {
		singleConn = redis_sync_connect_elastic(ip, port);
	}

	LOG_INFO("[%s:%d] NEW REDIS SINGLE CLIENT IP[%s] PORT[%d] over",
										__func__, __LINE__, ip, port);

	return (singleConn ? 0 : -1);
}

void
redis_single_disconnect(void)
{
	if (NULL == singleConn) {
		return;
	}

	LOG_DEBUG("[%s:%d] DISCONNECT SINGLE REDIS IP[%s] PORT[%d]",
					__func__, __LINE__, singleConn->ip, singleConn->port);
	redis_sync_free(singleConn);
	singleConn = NULL;
}

int
redis_single_init(void)
{
//	register_local_log_level("c.redis-single");
	LOG_DEBUG("[%s:%d] INIT SINGLE REDIS CONNECTION", __func__, __LINE__);
	return redis_single_connect();
}

void
redis_single_finit(void)
{
	LOG_DEBUG("[%s:%d] FINIT SINGLE REDIS CONNECTION", __func__, __LINE__);
	redis_single_disconnect();
}

struct redisReply*
redis_single_executev_result(const char* cmd, va_list arglist)
{
	if (NULL == singleConn) {
		LOG_INFO("[%s:%d] CMD can not be executed:redis single connection is not established", __func__, __LINE__);
		return NULL;
	}

	return redisSyncCommandv(singleConn, cmd, arglist);
}
